<?php

use Medoo\Medoo;

/**
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';

echo '爬虫开始' . PHP_EOL;

$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://www.tesla.cn/all-locations?type=service&bounds=3.52,73.40,53.33,135.230&deep&map=baidu');
$html = (string)$res->getBody();

$data = json_decode($html, true);
$db = new Medoo($config);
$db->delete('tDealer', ['sBrand' => '特斯拉']);

foreach ($data as $item) {

    $phone = $item['sales_phone'];
    $temp = array_map(function ($e) {
        return $e['label'] . $e['number'];
    }, $phone);
    $service_phone = implode(',', $temp);

    $db->insert('tDealer', [
        'sDealerName' => $item['title'],
        'nBrandID' => $item['trt_id'],
        'sBrand' => '特斯拉',
        'sProvince' => $item['province_state'],
        'sCity' => $item['city'],
        'sAddress' => $item['address'],
        'sSaleCall' => $service_phone,
        'sLatitude' => $item['latitude'],
        'sLongitude' => $item['longitude'],
        'dUpdateTime' => Medoo::raw('now()'),
        'sManufacturer' => '上海',
    ]);
    echo "{$item['title']}完成" . PHP_EOL;
}
echo '爬虫结束' . PHP_EOL;